<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :title="'审计疑点'"
    :visible.sync="visible"
    custom-class="ledger"
    fullscreen top="5vh"
    width="1200px"
    :before-close="cancelDialog">
    <div class="colums">
      <div class="colums_left">
        <div class="colums_left_middle">
          <div class="middleForm ledger" style="overflow-x: hidden">
            <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
<!--              <el-row>-->
<!--                <el-col :span="6">-->
<!--                  <el-form-item label="记录人:" prop="recordName">-->
<!--                    {{form.recordName}}-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
<!--                <el-col :span="6">-->
<!--                  <el-form-item label-width="100px" label="记录日期:">-->
<!--                    <el-date-picker placement="bottom-start" v-model="form.recordDate" type="date" placeholder="选择日期"></el-date-picker>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
<!--              </el-row>-->
              <div class="title">项目信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="项目名称:" prop="projectName" :rules="{required: true, message: '项目名称不能为空', trigger: ['focus', 'change']}">
                    <el-input v-model="form.projectName" placeholder="选择项目" @focus="showProjectDialog()" ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="300px" label="审计重点:" prop="projectName" >
                    <el-input v-model="form.keynoteTitle" placeholder="选择审计重点" @focus="showAuditFocus()" :rules="{required: true, message: '审计重点不能为空', trigger: ['focus', 'change']}"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">审计疑点</div>
<!--              <el-row>-->
<!--                <el-col :span="6">-->
<!--                  <el-form-item label-width="100px" label="是否落实:" prop="fix">-->
<!--                    <el-radio-group v-model="form.fix" :disabled="formDisplay">-->
<!--                      <el-radio :label="0">是</el-radio>-->
<!--                      <el-radio :label="1">否</el-radio>-->
<!--                    </el-radio-group>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
<!--                <el-col :span="6">-->
<!--                  <el-form-item label-width="100px" label="形成问题:" prop="discovery">-->
<!--                    <el-radio-group v-model="form.discovery" :disabled="formDisplay">-->
<!--                      <el-radio :label="0">是</el-radio>-->
<!--                      <el-radio :label="1">否</el-radio>-->
<!--                    </el-radio-group>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
<!--              </el-row>-->
              <el-row>
                <el-col>
                  <el-form-item label-width="100px"  label="疑点描述:" prop="pointDesc">
                    <el-input :disabled="formDisplay" v-model="form.pointDesc" :autosize="{ minRows: 2}" type="textarea"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">审计证据</div>
              <el-row>
                <el-col :span="24">
                  <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem">新建</el-button>
                    <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                  <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-table
                    ref="table"
                    :data="tableData"
                    :model="tableData"
                    style="width: 100%"
                    max-height="450"
                    highlight-current-row
                    @selection-change="updateSelectedRows"
                    @current-change="handleCurrentChange"
                  >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="序号" width="50">
                      <template #default="{ row, $index }">
                        <span>{{ $index+1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="证据类别">
                      <template #default="{ row }">
                        <el-select v-model="row.evidenceType" clearable>
                          <el-option v-for="dict in dict.type.evidence_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="取证日期">
                      <template #default="{ row }">
                        <el-date-picker v-model="row.evidenceDate" class="datePicker" format="yyyy-MM-dd" placeholder="选择日期" placement="bottom-start" type="date" value-format="yyyy-MM-dd"></el-date-picker>
                      </template>
                    </el-table-column>
                    <el-table-column label="相关附件">
                      <template #default="{ row, $index }">
                        <el-upload
                          class="upload-demo"
                          ref="upload"
                          action="/admin/sys-file/upload"
                          :headers="{Authorization}"
                          :on-success="(e) => handleSuccess(e, $index)"
                          :on-preview="handlePreview"
                          :on-remove="(file, fileList) => handleRemove(file, fileList, $index)"
                          :show-file-list="true"
                          :file-list="row.fileList">
                          <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                        </el-upload>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
      <el-button v-if="!formDisplay" icon="el-icon-check" size="small" type="primary" @click="submit">保存</el-button>
    </span>
    <formTransfer :multiple="multiple" :transferDialog="transferDialog" :transferDialogType="transferDialogType" @closeTransfer="closeTransfer" @transferData="transferDataHandle"/>
    <ChoseProject ref="ChoseProject" @setValue="projectDataHandle"/>
    <ChoseAuditFocus ref="AuditFocus" @setValue="auditFocusHandle"/>
  </el-dialog>
</template>

<script>
import FormTransfer from "@/components/form/transfer";
import ChoseProject from "@/components/audited/ChoseProject";
import ChoseAuditFocus from "@/components/audited/ChoseAuditFocus.vue";
import {submit,getByPointId} from "@/api/adis/execute/point";
import {getProject} from "@/api/adis/project/project";

export default {
  components: {
    FormTransfer,
    ChoseProject,
    ChoseAuditFocus
  },
  dictTypes: ['evidence_type'],
  data() {
    return {
      visible: false,
      formDisplay: false,
      canSubmit: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      templateForm: [],
      form: {},
      tableData: [], // 表格数据
      selectedRows: [], // 存储选中的行数据
      selectedRow: {},

      nextId: 2, // 序号计数器
      Authorization:''
    }
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  watch: {
    tableData(newVal){
      if (newVal.length < 1){
        this.onAddItem(this.tableData)
      }
    },
  },
  methods: {
    init(params, type) {
      this.canSubmit = true;
      this.formDisplay = type
      this.form.recordName = params.recordName;
      this.form.fix = 1;
      this.form.discovery = 1;
      this.form.recordDate = new Date().toISOString();
      this.$nextTick(async () => {
        if (params.pointId || params.projectId) {
          const response = await getByPointId(params.pointId);
          const data = { ...response.data.data };
          this.$set(data, 'auditArrayTime', [data.auditStartDate, data.auditEndDate]);
          this.$set(data, 'recordName', data.createBy);
          this.$set(data, 'recordDate', data.createTime);
          this.form = data;

          this.tableData = data.projectPointAttachments || [];
          this.tableData.forEach(item => {
            item.fileList = []
            item.attachments.forEach(col => {
              item.fileList.push({name: col.fileName, url: col.fileUrl})
            })
          })
          // getProject(params.projectId).then(projectResponse => {
          //   let combinedFormData = Object.assign({}, noticeResponse.data.data, projectResponse.data.data);
          //   this.$set(this, "form", combinedFormData);
          //   this.form.auditArrayTime = [combinedFormData.auditStartDate, combinedFormData.auditEndDate];
          //   // this.form.recordDate = new Date().toISOString()
          // })
        }
        this.visible = true;
      })
    },
    showProjectDialog() {
      this.$nextTick(() => {
        this.$refs.ChoseProject.initParams({
          // isCreateDoubtful: true,//用来创建疑点记录
          isProjectApproved: true,//项目是否审批完成
          isEngineering: false,
          isTermination: false});
      })
    },
    projectDataHandle(row) {
      this.templateForm = this.form
      let combinedFormData = Object.assign({}, this.form, row);
      this.$set(this, "form", combinedFormData);
      this.form.auditArrayTime = [row.auditStartDate, row.auditEndDate];
      this.form.workArrayTime = [row.workStartDate, row.workEndDate];
    },
    showAuditFocus() {
      this.$nextTick(() => {
        this.$refs.AuditFocus.initParams({projectId: this.form.projectId});
      })
    },
    auditFocusHandle(row) {
      this.templateForm = this.form
      let combinedFormData = Object.assign({}, this.form, row);
      this.$set(this, "form", combinedFormData);
    },
    clearProjectForm() {
      this.$set(this, "form", this.templateForm)
    },

    handleSuccess(e, v) {
      if (!this.tableData[v].fileList) {
        this.tableData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
        console.log(this.tableData);
      } else {
        this.tableData[v].fileList.push({url: e.data.url, name: e.data.fileName})
        console.log(this.tableData);
      }
    },
    handleRemove(file, fileList, i) {
      this.tableData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableData[i].fileList.splice(v, 1)
      })
    },
    handlePreview (file) {
      // const a = document.createElement('a');
      // let url = file.url ? file.url : file.response.data.url;
      // console.log(url);      // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      // a.setAttribute('download', file.name);
      // a.setAttribute('href', url);
      // a.click();
      window.open(file.url ? file.url : file.response.data.url)
    },

// -- 资料清单
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
      } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        evidenceType: val.evidenceType || '',
        evidenceDate: val.evidenceDate || '',
        fileList: val.fileList || [],
      })
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
      } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },

    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    // 表单提交
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(item.evidenceType === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行证据类型未选择"
                });
                count++
                throw Error();
              }
              if(item.evidenceDate === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行取证日期未填写"
                });
                count++
                throw Error();
              }
              if(!item.fileList || item.fileList.length === 0){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行资料附件不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.projectPointAttachments = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList){
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.projectPointAttachments.push(item)
          })
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    //重置表单
    cancelDialog() {
      this.visible = false;
      this.form = {};
      this.clearTableData();
      this.$refs['dataForm'].resetFields()
      this.$emit('cancelDialog', {})
    },
    showUserDialog(arr, type, multiple) {
      this.transferDialogTypeArr = arr
      this.transferDialogType = type
      this.multiple = multiple
      this.transferDialog = true
    },
    closeTransfer() {
      this.transferDialog = false
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentVal = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentVal.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentVal = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogTypeArr[0], currentLabel.join(','))
        this.$set(this.form, this.transferDialogTypeArr[1], currentVal.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogTypeArr[0], '')
        this.$set(this.form, this.transferDialogTypeArr[1], '')
      }
    },
  }
}
</script>
